﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading.Tasks;
using Net.Chirash.Twitter.TwitterClient;
using Net.Chirash.Twitter.TwitterDatabase;
using Net.Chirash.Twitter.TweetZone.WindowComponents.Containers;
using Net.Chirash.Twitter.TweetZone.WindowComponents.ViewModels;
using Net.Chirash.Twitter.TweetZone.Tools;

/* @Author: kanosaki_cp
 * MEMO:
 *	ユーザーに関する統計情報が表示出来れば良いかなと思い、広く空けておきました。
 *	TwitterClient.User.Profile***Colorなどの実装はしていません
 *	
 */
namespace Net.Chirash.Twitter.TweetZone
{
    /// <summary>
    /// ユーザープロフィールを表示します。
    /// また、表示しているユーザーが自分の場合はプロフィール編集機能が有効になります
    /// </summary>
    public partial class UserProfileWindow : Window
    {
        #region Public Properties

        User _user;
        public User User
        {
            get { return _user; }
            set
            {
                this.DataContext = value;
                MainGrid.DataContext = value;
                _user = value;

                //コードビハインドでUI更新処理を記述する場合はここに
                SetupBackground();

                TLPanel.ZoneContainerCollection.Clear();
                var tlViewModel = new TimelineContainerViewModel(TimelineTypes.User, _user) { IsDBOnly = false };

                TLPanel.AddContainer(typeof(TimelineContainer), tlViewModel);
                TLPanel.AddContainer(typeof(TwitterListsContainer), new TwitterListContainerViewModel(_user));
                TLPanel.AddContainer(typeof(UsersContainer), new UserContainerViewModel(UserListType.Friend, _user));
                TLPanel.AddContainer(typeof(UsersContainer), new UserContainerViewModel(UserListType.Follower, _user));

                TLPanel.RefreshAsync((containerVM) =>
                    {
                        if (containerVM is TimelineContainerViewModel)
                        {
                            (containerVM as TimelineContainerViewModel).IsDBOnly = false;
                            containerVM.RefreshAsync(null);
                        }
                    });

                //FollowToggleButtonの表示変化
                if (App.CurrentApp.User != null && value.UserID == App.CurrentApp.User.UserID)
                {
                    FollowToggleButton.Content = " ---- ";
                    FollowToggleButton.IsEnabled = false;
                }
                else if (value.IsFollowing)
                    FollowToggleButton.Content = "Unfollow";
                else
                    FollowToggleButton.Content = "Follow";


            }
        }

        #endregion

        #region Constructors

        public delegate void RoutedRefreshEventHandler();

        public UserProfileWindow()
        {
#if DEBUG
            try
            {
#endif
            InitializeComponent();
#if DEBUG
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
#endif
        }

        public UserProfileWindow(User user, bool show = false)
            : this()
        {
            User = user;
            if (show) this.Show();
        }

        #endregion

        #region Public Methods

        public void Show(User user)
        {
            User = user;
            Show();
        }

        public void SetupBackground()
        {
            if (User != null)
            {
                this.rootWindow.Background = new SolidColorBrush(System.Drawing.Color.FromArgb(User.ProfileBackgroundColor).ToWindowsMediaColor());

                if (User.ProfileUseBackgroundImage)
                {
                    var bmpsrc = new BitmapImage(new Uri(User.ProfileBackgroundImageUrl));
                    ImageBrush imgbr = new ImageBrush()
                    {
                        ImageSource = bmpsrc,
                        ViewportUnits = BrushMappingMode.Absolute,
                    };
                    ProfileBackground.Fill = imgbr;
                    bmpsrc.DownloadCompleted += (sender, e) =>
                        {
                            imgbr.Viewport = new Rect(0.0, 0.0, (double)bmpsrc.PixelWidth, (double)bmpsrc.PixelHeight);
                            imgbr.Stretch = Stretch.UniformToFill;
                            if (User.ProfileBackgroundTile)
                            {
                                imgbr.AlignmentX = AlignmentX.Left;
                                imgbr.AlignmentY = AlignmentY.Top;
                                imgbr.TileMode = TileMode.Tile;
                            }

                            if (bmpsrc.CanFreeze)
                                bmpsrc.Freeze();
                            if (imgbr.CanFreeze)
                                imgbr.Freeze();
                            ProfileBackground.Fill = imgbr;
                        };
                }
            }
        }

        #endregion

        #region Private Events

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void rootWindow_Closed(object sender, EventArgs e)
        {
            foreach (var item in this.TLPanel.ZoneContainerCollection)
            {
                item.Dispose();
                item.Composer.ContainerViewModel.UnSubscribe();
            }
        }

        #endregion

        private void BlockeToggleButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void FollowToggleButton_Click(object sender, RoutedEventArgs e)
        {
            var tc = new TwitterCommand(App.CurrentApp.Connection);
            try
            {
                if (this.User.IsFollowing)
                {
                    tc.DestroyFriendShip(this.User);
                    FollowToggleButton.Content = "Follow";
                }
                else
                {
                    tc.CreateFriendShip(this.User, true);
                    FollowToggleButton.Content = "Unfollow";
                }
            }
            catch (System.Net.WebException ex)
            {
                MessageBox.Show(ErrorMessageProvider.CreateErrorMessage(ex));
            }
        }
    }
}
